/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package pl.tom.social.analyzer.gui.component;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.openide.util.Exceptions;
import org.openide.util.NbBundle;
import org.openide.windows.TopComponent;
import org.openide.windows.WindowManager;
//import org.openide.util.ImageUtilities;
import org.netbeans.api.settings.ConvertAsProperties;
import org.openide.DialogDescriptor;
import org.openide.DialogDisplayer;
import pl.tom.social.analyzer.common.Results;
import pl.tom.social.analyzer.analysis.QuerySearch;
import pl.tom.social.analyzer.analysis.TermFreqCounter;
import pl.tom.social.analyzer.graph.GraphBuilder;
import pl.tom.social.analyzer.gui.panel.NewProfilePanel;
import pl.tom.social.analyzer.jade.LocalJade;
import pl.tom.social.analyzer.visualizer.AnalysisVisualizer;
import pl.tom.social.common.types.AnalysisType;
import pl.tom.social.common.types.ConversationIDType;
import pl.tom.social.common.utils.Converter;
import pl.tom.social.dal.SocialDatabaseFacade;
import pl.tom.social.dal.entity.Profile;
import pl.tom.social.dal.entity.Site;
import pl.tom.social.dal.entity.SiteEntry;

/**
 * Top component which displays something.
 */
@ConvertAsProperties(dtd = "-//pl.tom.social.analyzer.gui.component//Main//EN",
autostore = false)
public final class MainTopComponent extends TopComponent {

	private static final Logger logger = Logger.getLogger(MainTopComponent.class);
	private static MainTopComponent instance;
	/** path to the icon used by the component and its open action */
//    static final String ICON_PATH = "SET/PATH/TO/ICON/HERE";
	private static final String PREFERRED_ID = "MainTopComponent";

	public MainTopComponent() {
		initComponents();
		setName(NbBundle.getMessage(MainTopComponent.class, "CTL_MainTopComponent"));
		setToolTipText(NbBundle.getMessage(MainTopComponent.class, "HINT_MainTopComponent"));
//        setIcon(ImageUtilities.loadImage(ICON_PATH, true));
	}

	/** This method is called from within the constructor to
	 * initialize the form.
	 * WARNING: Do NOT modify this code. The content of this method is
	 * always regenerated by the Form Editor.
	 */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        topSplitPane = new javax.swing.JSplitPane();
        sitesPanel = new javax.swing.JPanel();
        sitesScrollPane = new javax.swing.JScrollPane();
        sitesList = new javax.swing.JList();
        rightPanel = new javax.swing.JPanel();
        analysisPanel = new javax.swing.JPanel();
        analysisResultScrollPane = new javax.swing.JScrollPane();
        analysisResultTable = new javax.swing.JTable();
        analysisIncludeLinksCheckBox = new javax.swing.JCheckBox();
        analysisSimpleButton = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        analysisSimpleSpinner = new javax.swing.JSpinner();
        jLabel2 = new javax.swing.JLabel();
        profileFindEntriesButton = new javax.swing.JButton();
        profileFindSitesButton = new javax.swing.JButton();
        profileNewButton = new javax.swing.JButton();
        profileDeleteButton = new javax.swing.JButton();
        graphPanel = new javax.swing.JPanel();
        includeEmptyCheckBox = new javax.swing.JCheckBox();
        datePanel = new javax.swing.JPanel();
        fromSpinner = new javax.swing.JSpinner();
        toSpinner = new javax.swing.JSpinner();
        fromLabel = new javax.swing.JLabel();
        toLabel = new javax.swing.JLabel();
        filterByDateCheckBox = new javax.swing.JCheckBox();
        showGraphButton = new javax.swing.JButton();
        infoPanel = new javax.swing.JPanel();
        sitesNrLabel = new javax.swing.JLabel();
        entriesNrLabel = new javax.swing.JLabel();
        commentsNrLabel = new javax.swing.JLabel();
        sitesNrInfo = new javax.swing.JLabel();
        entriesNrInfo = new javax.swing.JLabel();
        commentsNrInfo = new javax.swing.JLabel();
        globalStatusLabel = new javax.swing.JLabel();
        fetcherStatusLabel = new javax.swing.JLabel();
        watcherStatusLabel = new javax.swing.JLabel();
        globalStatusInfo = new javax.swing.JLabel();
        fetcherStatusInfo = new javax.swing.JLabel();
        watcherStatusInfo = new javax.swing.JLabel();
        jSeparator1 = new javax.swing.JSeparator();
        jSeparator2 = new javax.swing.JSeparator();
        selectedLinksLabel = new javax.swing.JLabel();
        selectedLinksInfo = new javax.swing.JLabel();
        deleteSiteButton = new javax.swing.JButton();
        selectedEntriesLabel = new javax.swing.JLabel();
        selectedEntriesInfo = new javax.swing.JLabel();
        updateSiteButton = new javax.swing.JButton();

        setAutoscrolls(true);
        setLayout(new java.awt.BorderLayout());

        topSplitPane.setDividerLocation(300);
        topSplitPane.setAutoscrolls(true);
        topSplitPane.setMaximumSize(new java.awt.Dimension(1024, 800));
        topSplitPane.setMinimumSize(new java.awt.Dimension(800, 800));
        topSplitPane.setPreferredSize(new java.awt.Dimension(800, 800));

        sitesPanel.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createEtchedBorder(), org.openide.util.NbBundle.getMessage(MainTopComponent.class, "MainTopComponent.sitesPanel.border.title"))); // NOI18N

        sitesScrollPane.setViewportView(sitesList);

        javax.swing.GroupLayout sitesPanelLayout = new javax.swing.GroupLayout(sitesPanel);
        sitesPanel.setLayout(sitesPanelLayout);
        sitesPanelLayout.setHorizontalGroup(
            sitesPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(sitesPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(sitesScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 267, Short.MAX_VALUE)
                .addContainerGap())
        );
        sitesPanelLayout.setVerticalGroup(
            sitesPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(sitesPanelLayout.createSequentialGroup()
                .addComponent(sitesScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 761, Short.MAX_VALUE)
                .addContainerGap())
        );

        topSplitPane.setLeftComponent(sitesPanel);

        analysisPanel.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createEtchedBorder(), org.openide.util.NbBundle.getMessage(MainTopComponent.class, "MainTopComponent.analysisPanel.border.title"))); // NOI18N

        analysisResultTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {},
                {}
            },
            new String [] {

            }
        ));
        analysisResultScrollPane.setViewportView(analysisResultTable);

        org.openide.awt.Mnemonics.setLocalizedText(analysisIncludeLinksCheckBox, org.openide.util.NbBundle.getMessage(MainTopComponent.class, "MainTopComponent.analysisIncludeLinksCheckBox.text")); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(analysisSimpleButton, org.openide.util.NbBundle.getMessage(MainTopComponent.class, "MainTopComponent.analysisSimpleButton.text")); // NOI18N
        analysisSimpleButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                analysisSimpleButtonActionPerformed(evt);
            }
        });

        org.openide.awt.Mnemonics.setLocalizedText(jLabel1, org.openide.util.NbBundle.getMessage(MainTopComponent.class, "MainTopComponent.jLabel1.text")); // NOI18N

        analysisSimpleSpinner.setModel(new javax.swing.SpinnerNumberModel(Integer.valueOf(100), Integer.valueOf(1), null, Integer.valueOf(1)));

        org.openide.awt.Mnemonics.setLocalizedText(jLabel2, org.openide.util.NbBundle.getMessage(MainTopComponent.class, "MainTopComponent.jLabel2.text")); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(profileFindEntriesButton, org.openide.util.NbBundle.getMessage(MainTopComponent.class, "MainTopComponent.profileFindEntriesButton.text")); // NOI18N
        profileFindEntriesButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                profileFindEntriesButtonActionPerformed(evt);
            }
        });

        org.openide.awt.Mnemonics.setLocalizedText(profileFindSitesButton, org.openide.util.NbBundle.getMessage(MainTopComponent.class, "MainTopComponent.profileFindSitesButton.text")); // NOI18N
        profileFindSitesButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                profileFindSitesButtonActionPerformed(evt);
            }
        });

        org.openide.awt.Mnemonics.setLocalizedText(profileNewButton, org.openide.util.NbBundle.getMessage(MainTopComponent.class, "MainTopComponent.profileNewButton.text")); // NOI18N
        profileNewButton.setMaximumSize(new java.awt.Dimension(89, 23));
        profileNewButton.setMinimumSize(new java.awt.Dimension(89, 23));
        profileNewButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                profileNewButtonActionPerformed(evt);
            }
        });

        org.openide.awt.Mnemonics.setLocalizedText(profileDeleteButton, org.openide.util.NbBundle.getMessage(MainTopComponent.class, "MainTopComponent.profileDeleteButton.text")); // NOI18N
        profileDeleteButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                profileDeleteButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout analysisPanelLayout = new javax.swing.GroupLayout(analysisPanel);
        analysisPanel.setLayout(analysisPanelLayout);
        analysisPanelLayout.setHorizontalGroup(
            analysisPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(analysisPanelLayout.createSequentialGroup()
                .addGroup(analysisPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(analysisPanelLayout.createSequentialGroup()
                        .addGroup(analysisPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(profileNewButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(profileDeleteButton, javax.swing.GroupLayout.DEFAULT_SIZE, 83, Short.MAX_VALUE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(analysisPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(profileFindSitesButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(profileFindEntriesButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                    .addGroup(analysisPanelLayout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(analysisSimpleSpinner, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jLabel2))
                    .addGroup(analysisPanelLayout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(analysisSimpleButton))
                    .addGroup(analysisPanelLayout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(analysisIncludeLinksCheckBox)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(analysisResultScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 272, Short.MAX_VALUE)
                .addContainerGap())
        );
        analysisPanelLayout.setVerticalGroup(
            analysisPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, analysisPanelLayout.createSequentialGroup()
                .addGroup(analysisPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(analysisResultScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 196, Short.MAX_VALUE)
                    .addGroup(analysisPanelLayout.createSequentialGroup()
                        .addGap(22, 22, 22)
                        .addComponent(analysisIncludeLinksCheckBox)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(analysisPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel1)
                            .addComponent(analysisSimpleSpinner, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel2))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(analysisSimpleButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 43, Short.MAX_VALUE)
                        .addGroup(analysisPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(profileNewButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(profileFindEntriesButton))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(analysisPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(profileDeleteButton)
                            .addComponent(profileFindSitesButton))))
                .addContainerGap())
        );

        graphPanel.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createEtchedBorder(), org.openide.util.NbBundle.getMessage(MainTopComponent.class, "MainTopComponent.graphPanel.border.title"))); // NOI18N
        graphPanel.setPreferredSize(new java.awt.Dimension(200, 334));

        org.openide.awt.Mnemonics.setLocalizedText(includeEmptyCheckBox, org.openide.util.NbBundle.getMessage(MainTopComponent.class, "MainTopComponent.includeEmptyCheckBox.text")); // NOI18N

        datePanel.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        datePanel.setEnabled(false);

        fromSpinner.setModel(new javax.swing.SpinnerDateModel(new java.util.Date(), null, null, java.util.Calendar.MONTH));

        toSpinner.setModel(new javax.swing.SpinnerDateModel(new java.util.Date(), null, null, java.util.Calendar.MONTH));

        org.openide.awt.Mnemonics.setLocalizedText(fromLabel, org.openide.util.NbBundle.getMessage(MainTopComponent.class, "MainTopComponent.fromLabel.text")); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(toLabel, org.openide.util.NbBundle.getMessage(MainTopComponent.class, "MainTopComponent.toLabel.text")); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(filterByDateCheckBox, org.openide.util.NbBundle.getMessage(MainTopComponent.class, "MainTopComponent.filterByDateCheckBox.text")); // NOI18N

        javax.swing.GroupLayout datePanelLayout = new javax.swing.GroupLayout(datePanel);
        datePanel.setLayout(datePanelLayout);
        datePanelLayout.setHorizontalGroup(
            datePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(datePanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(datePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(datePanelLayout.createSequentialGroup()
                        .addComponent(toLabel)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 26, Short.MAX_VALUE)
                        .addComponent(toSpinner, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(datePanelLayout.createSequentialGroup()
                        .addComponent(fromLabel)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 14, Short.MAX_VALUE)
                        .addComponent(fromSpinner, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(filterByDateCheckBox))
                .addContainerGap())
        );
        datePanelLayout.setVerticalGroup(
            datePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, datePanelLayout.createSequentialGroup()
                .addComponent(filterByDateCheckBox)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 4, Short.MAX_VALUE)
                .addGroup(datePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(fromLabel)
                    .addComponent(fromSpinner, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(datePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(toLabel)
                    .addComponent(toSpinner, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );

        org.openide.awt.Mnemonics.setLocalizedText(showGraphButton, org.openide.util.NbBundle.getMessage(MainTopComponent.class, "MainTopComponent.showGraphButton.text")); // NOI18N
        showGraphButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                showGraphButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout graphPanelLayout = new javax.swing.GroupLayout(graphPanel);
        graphPanel.setLayout(graphPanelLayout);
        graphPanelLayout.setHorizontalGroup(
            graphPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(graphPanelLayout.createSequentialGroup()
                .addComponent(datePanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(includeEmptyCheckBox)
                .addGap(80, 80, 80)
                .addComponent(showGraphButton)
                .addContainerGap())
        );
        graphPanelLayout.setVerticalGroup(
            graphPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(datePanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, graphPanelLayout.createSequentialGroup()
                .addContainerGap(54, Short.MAX_VALUE)
                .addGroup(graphPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(showGraphButton)
                    .addComponent(includeEmptyCheckBox))
                .addContainerGap())
        );

        infoPanel.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createEtchedBorder(), org.openide.util.NbBundle.getMessage(MainTopComponent.class, "MainTopComponent.infoPanel.border.title"))); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(sitesNrLabel, org.openide.util.NbBundle.getMessage(MainTopComponent.class, "MainTopComponent.sitesNrLabel.text")); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(entriesNrLabel, org.openide.util.NbBundle.getMessage(MainTopComponent.class, "MainTopComponent.entriesNrLabel.text")); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(commentsNrLabel, org.openide.util.NbBundle.getMessage(MainTopComponent.class, "MainTopComponent.commentsNrLabel.text")); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(sitesNrInfo, org.openide.util.NbBundle.getMessage(MainTopComponent.class, "MainTopComponent.sitesNrInfo.text")); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(entriesNrInfo, org.openide.util.NbBundle.getMessage(MainTopComponent.class, "MainTopComponent.entriesNrInfo.text")); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(commentsNrInfo, org.openide.util.NbBundle.getMessage(MainTopComponent.class, "MainTopComponent.commentsNrInfo.text")); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(globalStatusLabel, org.openide.util.NbBundle.getMessage(MainTopComponent.class, "MainTopComponent.globalStatusLabel.text")); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(fetcherStatusLabel, org.openide.util.NbBundle.getMessage(MainTopComponent.class, "MainTopComponent.fetcherStatusLabel.text")); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(watcherStatusLabel, org.openide.util.NbBundle.getMessage(MainTopComponent.class, "MainTopComponent.watcherStatusLabel.text")); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(globalStatusInfo, org.openide.util.NbBundle.getMessage(MainTopComponent.class, "MainTopComponent.globalStatusInfo.text")); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(fetcherStatusInfo, org.openide.util.NbBundle.getMessage(MainTopComponent.class, "MainTopComponent.fetcherStatusInfo.text")); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(watcherStatusInfo, org.openide.util.NbBundle.getMessage(MainTopComponent.class, "MainTopComponent.watcherStatusInfo.text")); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(selectedLinksLabel, org.openide.util.NbBundle.getMessage(MainTopComponent.class, "MainTopComponent.selectedLinksLabel.text")); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(selectedLinksInfo, org.openide.util.NbBundle.getMessage(MainTopComponent.class, "MainTopComponent.selectedLinksInfo.text")); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(deleteSiteButton, org.openide.util.NbBundle.getMessage(MainTopComponent.class, "MainTopComponent.deleteSiteButton.text")); // NOI18N
        deleteSiteButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                deleteSiteButtonActionPerformed(evt);
            }
        });

        org.openide.awt.Mnemonics.setLocalizedText(selectedEntriesLabel, org.openide.util.NbBundle.getMessage(MainTopComponent.class, "MainTopComponent.selectedEntriesLabel.text")); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(selectedEntriesInfo, org.openide.util.NbBundle.getMessage(MainTopComponent.class, "MainTopComponent.selectedEntriesInfo.text")); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(updateSiteButton, org.openide.util.NbBundle.getMessage(MainTopComponent.class, "MainTopComponent.updateSiteButton.text")); // NOI18N
        updateSiteButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                updateSiteButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout infoPanelLayout = new javax.swing.GroupLayout(infoPanel);
        infoPanel.setLayout(infoPanelLayout);
        infoPanelLayout.setHorizontalGroup(
            infoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(infoPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(infoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(infoPanelLayout.createSequentialGroup()
                        .addComponent(sitesNrLabel)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 403, Short.MAX_VALUE)
                        .addComponent(sitesNrInfo))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, infoPanelLayout.createSequentialGroup()
                        .addComponent(entriesNrLabel)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 396, Short.MAX_VALUE)
                        .addComponent(entriesNrInfo))
                    .addGroup(infoPanelLayout.createSequentialGroup()
                        .addComponent(commentsNrLabel)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 377, Short.MAX_VALUE)
                        .addComponent(commentsNrInfo))
                    .addComponent(jSeparator1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 456, Short.MAX_VALUE)
                    .addGroup(infoPanelLayout.createSequentialGroup()
                        .addComponent(globalStatusLabel)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 390, Short.MAX_VALUE)
                        .addComponent(globalStatusInfo))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, infoPanelLayout.createSequentialGroup()
                        .addComponent(fetcherStatusLabel)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 382, Short.MAX_VALUE)
                        .addComponent(fetcherStatusInfo))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, infoPanelLayout.createSequentialGroup()
                        .addComponent(watcherStatusLabel)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 378, Short.MAX_VALUE)
                        .addComponent(watcherStatusInfo))
                    .addComponent(jSeparator2, javax.swing.GroupLayout.DEFAULT_SIZE, 456, Short.MAX_VALUE)
                    .addGroup(infoPanelLayout.createSequentialGroup()
                        .addComponent(selectedLinksLabel)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 366, Short.MAX_VALUE)
                        .addComponent(selectedLinksInfo))
                    .addGroup(infoPanelLayout.createSequentialGroup()
                        .addComponent(selectedEntriesLabel)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 353, Short.MAX_VALUE)
                        .addComponent(selectedEntriesInfo))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, infoPanelLayout.createSequentialGroup()
                        .addComponent(updateSiteButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 286, Short.MAX_VALUE)
                        .addComponent(deleteSiteButton)))
                .addContainerGap())
        );
        infoPanelLayout.setVerticalGroup(
            infoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(infoPanelLayout.createSequentialGroup()
                .addGroup(infoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(sitesNrLabel)
                    .addComponent(sitesNrInfo))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(infoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(entriesNrInfo)
                    .addComponent(entriesNrLabel))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(infoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(commentsNrLabel)
                    .addComponent(commentsNrInfo))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(infoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(globalStatusLabel)
                    .addComponent(globalStatusInfo))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(infoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(fetcherStatusInfo)
                    .addComponent(fetcherStatusLabel))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(infoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(watcherStatusInfo)
                    .addComponent(watcherStatusLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 19, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(infoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(selectedLinksLabel)
                    .addComponent(selectedLinksInfo))
                .addGap(11, 11, 11)
                .addGroup(infoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(selectedEntriesLabel)
                    .addComponent(selectedEntriesInfo))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 159, Short.MAX_VALUE)
                .addGroup(infoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(deleteSiteButton)
                    .addComponent(updateSiteButton))
                .addContainerGap())
        );

        javax.swing.GroupLayout rightPanelLayout = new javax.swing.GroupLayout(rightPanel);
        rightPanel.setLayout(rightPanelLayout);
        rightPanelLayout.setHorizontalGroup(
            rightPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, rightPanelLayout.createSequentialGroup()
                .addGroup(rightPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(infoPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(graphPanel, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 488, Short.MAX_VALUE)
                    .addComponent(analysisPanel, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addGap(6, 6, 6))
        );
        rightPanelLayout.setVerticalGroup(
            rightPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(rightPanelLayout.createSequentialGroup()
                .addComponent(analysisPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(graphPanel, javax.swing.GroupLayout.PREFERRED_SIZE, 114, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(infoPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        topSplitPane.setRightComponent(rightPanel);

        add(topSplitPane, java.awt.BorderLayout.CENTER);
    }// </editor-fold>//GEN-END:initComponents

	private void updateSiteButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_updateSiteButtonActionPerformed
		Object[] objs = sitesList.getSelectedValues();
		for (Object obj : objs) {
			if (obj instanceof Site) {
				Site site = (Site) obj;
				LocalJade.getInstance().addFetcherAgent(site.getUrl(), ConversationIDType.UpdateNode);
			}
		}
	}//GEN-LAST:event_updateSiteButtonActionPerformed

	private void deleteSiteButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deleteSiteButtonActionPerformed
		Object[] objs = sitesList.getSelectedValues();
		for (Object obj : objs) {
			if (obj instanceof Site) {
				SocialDatabaseFacade db = new SocialDatabaseFacade();
				Site site;
				try {
					//TODO change to id
					site = db.getSite(((Site) obj).getUrl());
					db.deleteEntity(site);
				} catch (Exception ex) {
					Exceptions.printStackTrace(ex);
				}
			}
		}
	}//GEN-LAST:event_deleteSiteButtonActionPerformed

	private void analysisSimpleButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_analysisSimpleButtonActionPerformed
		List<Site> sites = Converter.convertToSiteList(sitesList.getSelectedValues());
		boolean save = false;
		int limit = (Integer) analysisSimpleSpinner.getValue();

		if (sites.size() > 0) {
			DefaultTableModel model = null;
			for (int i = 0; i < sites.size(); i++) {
				TermFreqCounter termCounter = new TermFreqCounter(sites.get(i), save);
				model = AnalysisVisualizer.termFreqToJTable(model, sites.get(i).getUrl(), termCounter, limit);
			}

			Results.show(model, AnalysisType.WordCount);
		} else {
			//TODO notify user
		}
	}//GEN-LAST:event_analysisSimpleButtonActionPerformed

	private void profileFindEntriesButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_profileFindEntriesButtonActionPerformed
		int row = analysisResultTable.getSelectedRow();
		if (row > -1) {
			String query = analysisResultTable.getValueAt(row, 1).toString();
			List<Site> sites = Converter.convertToSiteList(sitesList.getSelectedValues());
			Map<String, Float> result = QuerySearch.getEntriesScore(query, sites);
			Results.show(AnalysisVisualizer.queryToJTable(result), AnalysisType.SimilaritiesSearch);
		} else {
			//TODO notify user
		}
	}//GEN-LAST:event_profileFindEntriesButtonActionPerformed

	private void profileFindSitesButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_profileFindSitesButtonActionPerformed
		int row = analysisResultTable.getSelectedRow();
		if (row > -1) {
			String query = analysisResultTable.getValueAt(row, 1).toString();
			List<Site> sites = Converter.convertToSiteList(sitesList.getSelectedValues());
			Map<String, Float> result = QuerySearch.getSitesScore(query, sites);
			Results.show(AnalysisVisualizer.queryToJTable(result), AnalysisType.SimilaritiesSearch);
		} else {
			//TODO notify user
		}
	}//GEN-LAST:event_profileFindSitesButtonActionPerformed

	private void profileNewButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_profileNewButtonActionPerformed
		final NewProfilePanel panel = new NewProfilePanel();

		final DialogDescriptor dialog = new DialogDescriptor(panel, "New profile", true, new ActionListener() {

			public void actionPerformed(ActionEvent e) {
				if (e.getSource() == DialogDescriptor.OK_OPTION) {
					SocialDatabaseFacade db = new SocialDatabaseFacade();
					Profile p = new Profile(panel.getQueryName(), panel.getQuery());
					db.persistEntity(p);
				}
			}
		});
		DialogDisplayer.getDefault().notify(dialog);
	}//GEN-LAST:event_profileNewButtonActionPerformed

	private void profileDeleteButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_profileDeleteButtonActionPerformed
		SocialDatabaseFacade db = new SocialDatabaseFacade();
		int[] rows = analysisResultTable.getSelectedRows();
		for (int row : rows) {
			String url = analysisResultTable.getModel().getValueAt(row, 0).toString();
			try {
				Profile p = db.getProfile(url);
				db.deleteEntity(p);
			} catch (Exception ex) {
				logger.log(Level.ERROR, null, ex);
			}
		}
		setProfiles();
	}//GEN-LAST:event_profileDeleteButtonActionPerformed

	private void showGraphButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_showGraphButtonActionPerformed
		List<Site> sites = new ArrayList<Site>();

		for (Object obj : sitesList.getSelectedValues()) {
			if (obj instanceof Site) {
				sites.add((Site) obj);
			}
		}

		GraphBuilder graphBuilder = new GraphBuilder(sites);
		graphBuilder.setLinks(includeEmptyCheckBox.isSelected());
		graphBuilder.setStart((Date) fromSpinner.getValue());
		graphBuilder.setEnd((Date) toSpinner.getValue());

		GraphTopComponent window = new GraphTopComponent(graphBuilder);
		window.open();
		window.requestActive();
	}//GEN-LAST:event_showGraphButtonActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JCheckBox analysisIncludeLinksCheckBox;
    private javax.swing.JPanel analysisPanel;
    private javax.swing.JScrollPane analysisResultScrollPane;
    private javax.swing.JTable analysisResultTable;
    private javax.swing.JButton analysisSimpleButton;
    private javax.swing.JSpinner analysisSimpleSpinner;
    private javax.swing.JLabel commentsNrInfo;
    private javax.swing.JLabel commentsNrLabel;
    private javax.swing.JPanel datePanel;
    private javax.swing.JButton deleteSiteButton;
    private javax.swing.JLabel entriesNrInfo;
    private javax.swing.JLabel entriesNrLabel;
    private javax.swing.JLabel fetcherStatusInfo;
    private javax.swing.JLabel fetcherStatusLabel;
    private javax.swing.JCheckBox filterByDateCheckBox;
    private javax.swing.JLabel fromLabel;
    private javax.swing.JSpinner fromSpinner;
    private javax.swing.JLabel globalStatusInfo;
    private javax.swing.JLabel globalStatusLabel;
    private javax.swing.JPanel graphPanel;
    private javax.swing.JCheckBox includeEmptyCheckBox;
    private javax.swing.JPanel infoPanel;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JSeparator jSeparator2;
    private javax.swing.JButton profileDeleteButton;
    private javax.swing.JButton profileFindEntriesButton;
    private javax.swing.JButton profileFindSitesButton;
    private javax.swing.JButton profileNewButton;
    private javax.swing.JPanel rightPanel;
    private javax.swing.JLabel selectedEntriesInfo;
    private javax.swing.JLabel selectedEntriesLabel;
    private javax.swing.JLabel selectedLinksInfo;
    private javax.swing.JLabel selectedLinksLabel;
    private javax.swing.JButton showGraphButton;
    private javax.swing.JList sitesList;
    private javax.swing.JLabel sitesNrInfo;
    private javax.swing.JLabel sitesNrLabel;
    private javax.swing.JPanel sitesPanel;
    private javax.swing.JScrollPane sitesScrollPane;
    private javax.swing.JLabel toLabel;
    private javax.swing.JSpinner toSpinner;
    private javax.swing.JSplitPane topSplitPane;
    private javax.swing.JButton updateSiteButton;
    private javax.swing.JLabel watcherStatusInfo;
    private javax.swing.JLabel watcherStatusLabel;
    // End of variables declaration//GEN-END:variables

	/**
	 * Gets default instance. Do not use directly: reserved for *.settings files only,
	 * i.e. deserialization routines; otherwise you could get a non-deserialized instance.
	 * To obtain the singleton instance, use {@link #findInstance}.
	 */
	public static synchronized MainTopComponent getDefault() {
		if (instance == null) {
			instance = new MainTopComponent();
		}
		return instance;
	}

	/**
	 * Obtain the MainTopComponent instance. Never call {@link #getDefault} directly!
	 */
	public static synchronized MainTopComponent findInstance() {
		TopComponent win = WindowManager.getDefault().findTopComponent(PREFERRED_ID);
		if (win == null) {
			Logger.getLogger(MainTopComponent.class.getName()).warn(
				"Cannot find " + PREFERRED_ID + " component. It will not be located properly in the window system.");
			return getDefault();
		}
		if (win instanceof MainTopComponent) {
			return (MainTopComponent) win;
		}
		Logger.getLogger(MainTopComponent.class.getName()).warn(
			"There seem to be multiple components with the '" + PREFERRED_ID
			+ "' ID. That is a potential source of errors and unexpected behavior.");
		return getDefault();
	}

	@Override
	public int getPersistenceType() {
		return TopComponent.PERSISTENCE_NEVER;
	}

	@Override
	public void componentOpened() {
		final SocialDatabaseFacade db = new SocialDatabaseFacade();
		setSites(db);
		setGraph(db);
		setProfiles();
		setInfo();
	}

	@Override
	public void componentClosed() {
	}

	void writeProperties(java.util.Properties p) {
		// better to version settings since initial version as advocated at
		// http://wiki.apidesign.org/wiki/PropertyFiles
		p.setProperty("version", "1.0");
	}

	Object readProperties(java.util.Properties p) {
		MainTopComponent singleton = MainTopComponent.getDefault();
		singleton.readPropertiesImpl(p);
		return singleton;
	}

	private void readPropertiesImpl(java.util.Properties p) {
		String version = p.getProperty("version");
	}

	@Override
	protected String preferredID() {
		return PREFERRED_ID;
	}

	private void setSites(final SocialDatabaseFacade db) {
		List<Site> sites = db.getAllSites();
		sitesList.setListData(sites.toArray());
		sitesList.addMouseListener(new MouseAdapter() {

			@Override
			public void mouseClicked(MouseEvent e) {
				if (e.getClickCount() == 2 && e.getButton() == MouseEvent.BUTTON1) {
					Object o = sitesList.getSelectedValue();
					if (o != null && o instanceof Site) {
						Site site = (Site) o;
						SiteTopComponent window = new SiteTopComponent(site);
						window.open();
						window.requestActive();
					}
				}
			}
		});
		sitesList.addListSelectionListener(new ListSelectionListener() {

			public void valueChanged(ListSelectionEvent e) {
				Long linksNr = 0l;
				Long entriesNr = 0l;

				Object obj = sitesList.getSelectedValue();
				if (obj instanceof Site) {
					Site site = (Site) obj;
					entriesNr = db.getSiteEntriesNr(site);
					linksNr = db.getSiteLinksNr(site);
				}
				selectedLinksInfo.setText(linksNr.toString());
				selectedEntriesInfo.setText(entriesNr.toString());
			}
		});
	}

	private void setGraph(SocialDatabaseFacade db) {
		Date oldest = new Date();
		Date newest = new Date();

		fromSpinner.setValue(oldest);
		toSpinner.setValue(newest);
	}

	private void setInfo() {
		SocialDatabaseFacade db = new SocialDatabaseFacade();
		sitesNrInfo.setText(db.getSitesNr().toString());
		entriesNrInfo.setText(db.getSiteEntriesNr().toString());
		commentsNrInfo.setText(db.getSiteEntryCommentsNr().toString());
		globalStatusInfo.setText(LocalJade.getInstance().getGlobalStatus());
		fetcherStatusInfo.setText(LocalJade.getInstance().getFetcherStatus());
		watcherStatusInfo.setText(LocalJade.getInstance().getWatcherStatus());
	}

	private void setProfiles() {
		DefaultTableModel model = AnalysisVisualizer.profilesToJTable();
		analysisResultTable.setModel(model);
		TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel>(model);
		analysisResultTable.setRowSorter(sorter);
	}
}
